package easeui.widget.chatrow;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.Spannable;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.BrowseActivity;
import com.github.postsanf.yinian.activity.MemoryCardDetailActivity;
import com.github.postsanf.yinian.activity.StatusDetailActivity;
import com.github.postsanf.yinian.activity.TimeCardDetailActivity;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.LinkedHashMap;

import easeui.utils.EaseSmileUtils;
import easeui.utils.TextBase64Util;

public class EaseChatRowHistoryText extends EaseChatHistoryRow {

    private TextView contentView;
    private RelativeLayout bubble_text;
    private RelativeLayout card_view;
    private TextView card_title;
    private SimpleDraweeView card_pic;
    private ImageView card_tip;


    public EaseChatRowHistoryText(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
    }

    @Override
    protected void onInflateView() {
        inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ?
                R.layout.ease_row_received_message : R.layout.ease_row_sent_message, this);
    }

    @Override
    protected void onFindViewById() {
        contentView = (TextView) findViewById(R.id.tv_chatcontent);
        bubble_text = (RelativeLayout) findViewById(R.id.bubble_text);
        card_view = (RelativeLayout) findViewById(R.id.card_view);
        card_title = (TextView) findViewById(R.id.card_title);
        card_pic = (SimpleDraweeView) findViewById(R.id.card_pic);
        card_tip = (ImageView) findViewById(R.id.card_tip);
    }

    private int eid;
    private String msgId;
    private String type;

    @Override
    public void onSetUpView() {
        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
        String boby = txtBody.getMessage();
        Log.i("xjs", "boby===>" + boby);
        Spannable span = EaseSmileUtils.getSmiledText(context, TextBase64Util.decode(boby));
        // 设置内容
        contentView.setText(span, BufferType.SPANNABLE);
        msgId = message.getMsgId();
        type = message.getStringAttribute("type", null);
        String pic = message.getStringAttribute("fristpic", "");
        eid = message.getIntAttribute("eventId", 0);
        Log.i("xjs", "fristpic===>" + pic);
        if (!StringUtils.isEmpty(type) && type.equals("66") || boby.contains("邀请你加入了群聊")|| boby.contains("退出了")) {
            card_view.setVisibility(View.GONE);
            bubble_text.setVisibility(View.GONE);
//            tv_userid.setVisibility(View.GONE);
        } else {
//            tv_userid.setVisibility(View.VISIBLE);
            card_view.setVisibility(View.VISIBLE);
            bubble_text.setVisibility(View.VISIBLE);
            if (message.direct() == EMMessage.Direct.SEND) {
                if (!StringUtils.isEmpty(type) && !type.equals("-1")) {
                    bubble_text.setVisibility(View.GONE);
                    card_view.setVisibility(View.VISIBLE);
                    card_title.setText(TextBase64Util.decode(boby));
                    ImageOptHelper.showFrescoStatus(Uri.parse(pic), card_pic, context);
                    if (type.equals("1")) {
                        card_tip.setImageResource(R.drawable.item_memorytitle);
                        card_tip.setVisibility(View.VISIBLE);
                    } else if (type.equals("3")) {
                        card_tip.setImageResource(R.drawable.item_daysigntt);
                        card_tip.setVisibility(View.VISIBLE);
                    } else {
                        card_tip.setVisibility(View.GONE);
                    }
                } else {
                    card_view.setVisibility(View.GONE);
                    bubble_text.setVisibility(View.VISIBLE);
                }
            } else {
                if (!StringUtils.isEmpty(type) && !type.equals("-1")) {
                    bubble_text.setVisibility(View.GONE);
                    card_view.setVisibility(View.VISIBLE);
                    card_title.setText(TextBase64Util.decode(boby));
                    ImageOptHelper.showFrescoStatus(Uri.parse(pic), card_pic, context);
                    if (type.equals("1")) {
                        card_tip.setImageResource(R.drawable.item_memorytitle);
                        card_tip.setVisibility(View.VISIBLE);
                    } else if (type.equals("3")) {
                        card_tip.setImageResource(R.drawable.item_daysigntt);
                        card_tip.setVisibility(View.VISIBLE);
                    } else {
                        card_tip.setVisibility(View.GONE);
                    }
                } else {
                    card_view.setVisibility(View.GONE);
                    bubble_text.setVisibility(View.VISIBLE);
                }
            }
            handleTextMessage();
        }

    }


    private void doChatContent(final int eid, final String type, final String msgId) {
        Log.i("xjs", "doChatContent==type=>" + type);
        if (type!=null&&type.equals("-1"))
            return;
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(eid));
        StringRequest req = new StringRequest(context.getString(R.string.BASE_URL) + context.getString(R.string.ynShowSingleEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "doChatContent==sss=>" + s.toString());
                        YNStatusResponse resSingleStatus = new Gson().fromJson(s, YNStatusResponse.class);
                        if (resSingleStatus != null && ReqUtils.isSuccess(resSingleStatus.getCode())) {
                            YNStatus status = resSingleStatus.getData().get(0);
                            if (status == null) {
                                return;
                            }
                            YNSingleton.getInstance().setCurStatus(status);
                            switch (Integer.parseInt(type)) {
                                case 0:
                                    lookStatus(eid);
                                    Intent intent = new Intent(context, StatusDetailActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                                    intent.putExtra("lookPeople", "lookPeople");
                                    context.startActivity(intent);
                                    break;
                                case 1:
                                    lookStatus(eid);
                                    Intent intent1 = new Intent(context, MemoryCardDetailActivity.class);
                                    intent1.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                                    intent1.putExtra("lookStatus", "lookStatus");
                                    context.startActivity(intent1);
                                    break;
                                case 2:
                                    lookStatus(eid);
                                    Intent intent2 = new Intent(context, TimeCardDetailActivity.class);
                                    intent2.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                                    intent2.putExtra("lookLimeCard", "lookLimeCard");
                                    context.startActivity(intent2);
                                    break;
                                case 3:
                                    lookStatus(eid);
                                    Intent dsIntent= new Intent(context, BrowseActivity.class);
                                    dsIntent.putExtra(CommonConstants.YNPOSITION, 0);
                                    dsIntent.putExtra("isDaySign",true);
                                    context.startActivity(dsIntent);
                                    break;
                            }
                        } else if (ReqUtils.is1027(resSingleStatus.getCode())) {
                            new AlertDialog.Builder(context).setMessage("动态不存在，确认删除")
                                    .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            context.sendBroadcast(new Intent(ACTIONs.actionChatDelteStatus).putExtra("msgId", msgId));
                                        }
                                    }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                }
                            }).show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(context)).executeAsync(req);
    }


    private void lookStatus(int eid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        Activity activity = (Activity) context;
        BaseApplication application = (BaseApplication) activity.getApplication();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put("eventid", String.valueOf(eid));
        StringRequest req = new StringRequest(context.getString(R.string.BASE_URL) + context.getString(R.string.ynWatchStatus))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        super.onSuccess(s, response);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(context, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(context)).executeAsync(req);
    }

    protected void handleTextMessage() {
        if (message.direct() == EMMessage.Direct.SEND) {
            setMessageSendCallback();
            switch (message.status()) {
                case CREATE:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.GONE);
                    break;
                case FAIL:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case INPROGRESS:
                    progressBar.setVisibility(View.VISIBLE);
                    statusView.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        } else {
            if (!message.isAcked() && message.getChatType() == ChatType.Chat) {
                try {
                    EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onUpdateView() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onBubbleClick() {
        // TODO Auto-generated method stub
        Log.i("xjs", "onBubbleClick==============w2e4q23r4");
        doChatContent(eid, type, msgId);
    }


}
